<template>
  <div class="search-novel-wrap">
    <van-search v-model="searchVal" placeholder="输入小说名称" shape="round" @search="onSearchNovel"></van-search>
    <div class="search-result" v-show="searchLoading || searchData.length">
      <div class="result-wrap">
        <div class="search-novel-loading">
          <loading :loading="searchLoading"/>
        </div>
        <div v-show="!searchLoading">
          <p class="result-item" v-for="(item,index) in searchData" :key="index"
             @click="toNovelDetail(item)">
            {{item}}
          </p>
        </div>
      </div>
      <div class="result-mask" @click="closeSearch"></div>
    </div>
  </div>
</template>
<script lang="ts">
  import {Component, Vue} from "vue-property-decorator";
  import {Search} from "vant";
  import loading from "@/components/loading.vue";

  @Component({
    components: {
      [Search.name]: Search,
      loading
    }
  })
  export default class NovelSearch extends Vue {
    private searchLoading: boolean = false;
    private searchVal: string = "";
    private searchData: string[] = [];

    // 跳转详情
    toNovelDetail(name:string) {
      this.$router.push({
        name: "novelDetail",
        query: {name}
      });
    }

    // 搜索小说
    onSearchNovel(name: string = this.searchVal) {
      if (!name) {
        return;
      }
      this.searchLoading = true;
      this.$api
        .get("/novelSearchApi", {name})
        .then((res: any) => {
          if (res && res.length) {
            this.searchData = res;
          }
        })
        .catch((e:any) => this.$toast(e.msg))
        .finally(() => {
          this.searchLoading = false;
        });
    }

    // 关闭搜索弹窗
    closeSearch() {
      this.searchLoading = false;
      this.searchData = [];
    }

  }
</script>
<style lang="scss">
  .search-novel-wrap {
    .search-result {
      width: 100%;
      height: 100%;
      position: fixed;
      left: 0;
      top: 40px;
      z-index: 10;
      .result-wrap {
        width: 100%;
        min-height: 200px;
        max-height: 300px;
        overflow-y: auto;
        position: absolute;
        top: -1px;
        left: 0;
        z-index: 10;
        background: #fff;
        .result-item {
          padding: 0 28px;
          height: 40px;
          line-height: 40px;
          border-bottom: 1px solid #eee;
          &:last-child {
            border-bottom: 0;
          }
        }
      }
      .result-mask {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, .4);
        z-index: 9;
      }
    }
  }
</style>


